package ogs.lib.mina.filter.codec
{
	import flash.utils.ByteArray;
	import flash.utils.Endian;
	
	import ogs.lib.mina.core.filterchain.NextFilter;

	public class ProtocolEncoderOutputImpl implements ProtocolEncoderOutput
	{
		private var messageQueue:Array = [];
		
		private var buffersOnly:Boolean = true;

		private var nextFilter:NextFilter;
		
		public function ProtocolEncoderOutputImpl(nextFilter:NextFilter) 
		{
			this.nextFilter = nextFilter;
		}
		
		public function getMessageQueue():Array
		{
			return messageQueue;
		}


		public function write(encodedMessage:Object):void
		{
			if (!encodedMessage)
				return;
			
			if (!(encodedMessage is ByteArray))
			{
				throw new ArgumentError("the encoded message must be a ByteArray.");
			}
			
			var buf:ByteArray = ByteArray(encodedMessage);
			buf.position = 0;
			messageQueue.push(buf);
		}
		
		public function mergeAll():void
		{
			var size:int = messageQueue.length;
			if (size < 2) {
				return;
			}
			
			var newBuf:ByteArray = new ByteArray();
			newBuf.endian = Endian.LITTLE_ENDIAN;
			
			while (messageQueue.length > 0) {
				var buf:ByteArray = messageQueue.shift();
				if (buf == null) {
					continue;
				}
				newBuf.writeBytes(buf, buf.position, buf.bytesAvailable);
			}
			messageQueue.push(newBuf);
		}
		
		public function flush():void
		{
			var messageQueue:Array = getMessageQueue();
			while (messageQueue.length) {
				nextFilter.filterWrite(messageQueue.shift());
			}
		}
	}
}